/**
 * @param  ele          要生成 pdf 的DOM元素（容器）
 * @param  padfName     PDF文件生成后的文件名字
 * */

import html2Canvas from 'html2canvas';
import JsPDF from 'jspdf';

const downloadPDF = function (ele, pdfName) {
  let height = ele.scrollHeight + 150;
  html2Canvas(ele, {
    useCORS: true, //保证跨域图片的显示
    allowTaint: false,
    height,
    windowHeight: height,
  }).then(function (canvas) {
    let contentWidth = canvas.width;
    let contentHeight = canvas.height;
    console.log(contentWidth, contentHeight, 1111);
    let pageHeight = (contentWidth / 592.28) * 841.89;
    let leftHeight = contentHeight;
    let position = 0;
    let imgWidth = 595.28;
    let imgHeight = (592.28 / contentWidth) * contentHeight;
    console.log(imgHeight, 2222);
    let pageData = canvas.toDataURL('image/jpeg', 1.0);
    let PDF = new JsPDF('', 'pt', 'a4');
    if (leftHeight < pageHeight) {
      PDF.addImage(pageData, 'JPEG', 0, 0, imgWidth, imgHeight);
    } else {
      while (leftHeight > 0) {
        PDF.addImage(pageData, 'JPEG', 0, position, imgWidth, imgHeight);
        leftHeight -= pageHeight;
        position -= 841.89;
        if (leftHeight > 0) {
          PDF.addPage();
        }
      }
    }
    PDF.save(pdfName + '.pdf');
  });
};

export { downloadPDF };
